<template>
  <div class="host-management">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>主机管理</span>
          <div class="header-actions">
            <el-button type="success" @click="handleBatchImport">
              <el-icon><Upload /></el-icon>
              批量导入
            </el-button>
            <el-button type="primary" @click="showAddDialog">
              <el-icon><Plus /></el-icon>
              添加主机
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-form :inline="true" :model="searchForm">
          <el-form-item label="主机名称">
            <el-input
              v-model="searchForm.name"
              placeholder="请输入主机名称或IP"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="主机类型">
            <el-select
              v-model="searchForm.hostType"
              placeholder="请选择主机类型"
              clearable
              style="width: 150px"
            >
              <el-option
                v-for="type in hostTypeOptions"
                :key="type.code"
                :label="type.name"
                :value="type.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="环境">
            <el-select
              v-model="searchForm.environment"
              placeholder="请选择环境"
              clearable
              style="width: 120px"
            >
              <el-option
                v-for="env in environmentOptions"
                :key="env.code"
                :label="env.name"
                :value="env.code"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select
              v-model="searchForm.status"
              placeholder="请选择状态"
              clearable
              style="width: 120px"
            >
              <el-option label="在线" value="online" />
              <el-option label="离线" value="offline" />
              <el-option label="维护中" value="maintenance" />
              <el-option label="故障" value="error" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              搜索
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 主机表格 -->
      <el-table
        :data="hostList"
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="hostname" label="主机名" min-width="150" />
        <el-table-column prop="ip" label="IP地址" width="140" />
        <el-table-column prop="hostType" label="主机类型" width="120">
          <template #default="{ row }">
            <el-tag :color="getHostTypeColor(row.hostType)">
              {{ getHostTypeName(row.hostType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="environment" label="环境" width="100">
          <template #default="{ row }">
            <el-tag :type="getEnvironmentTagType(row.environment)">
              {{ getEnvironmentName(row.environment) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTagType(row.status)">
              {{ getStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="specs" label="配置信息" min-width="200">
          <template #default="{ row }">
            <div class="specs-info">
              <div>CPU: {{ row.specs.cpu }}核</div>
              <div>内存: {{ row.specs.memory }}GB</div>
              <div>磁盘: {{ row.specs.disk }}GB</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="os" label="操作系统" width="150" />
        <el-table-column prop="hostGroup" label="主机组" width="120" />
        <el-table-column prop="lastHeartbeat" label="最后心跳" width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              @click="showDetailDialog(row)"
            >
              详情
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showEditDialog(row)"
            >
              编辑
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="handleConnect(row)"
            >
              连接
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDelete(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 批量操作栏 -->
      <div class="batch-actions" v-if="selectedHosts.length > 0">
        <span>已选择 {{ selectedHosts.length }} 台主机</span>
        <el-button type="warning" size="small" @click="handleBatchEdit">批量编辑</el-button>
        <el-button type="info" size="small" @click="handleBatchConnect">批量连接</el-button>
        <el-button type="danger" size="small" @click="handleBatchDelete">批量删除</el-button>
      </div>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 添加/编辑主机对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="900px"
      @close="resetForm"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-tabs v-model="activeTab">
          <el-tab-pane label="基本信息" name="basic">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="主机名" prop="hostname">
                  <el-input v-model="form.hostname" placeholder="请输入主机名" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="IP地址" prop="ip">
                  <el-input v-model="form.ip" placeholder="请输入IP地址" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="主机类型" prop="hostType">
                  <el-select v-model="form.hostType" placeholder="请选择主机类型" style="width: 100%">
                    <el-option
                      v-for="type in hostTypeOptions"
                      :key="type.code"
                      :label="type.name"
                      :value="type.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="环境" prop="environment">
                  <el-select v-model="form.environment" placeholder="请选择环境" style="width: 100%">
                    <el-option
                      v-for="env in environmentOptions"
                      :key="env.code"
                      :label="env.name"
                      :value="env.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="主机组" prop="hostGroup">
                  <el-select v-model="form.hostGroup" placeholder="请选择主机组" style="width: 100%">
                    <el-option
                      v-for="group in hostGroupOptions"
                      :key="group.code"
                      :label="group.name"
                      :value="group.code"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="操作系统" prop="os">
                  <el-select v-model="form.os" placeholder="请选择操作系统" style="width: 100%">
                    <el-option label="CentOS 7" value="centos7" />
                    <el-option label="CentOS 8" value="centos8" />
                    <el-option label="Ubuntu 18.04" value="ubuntu1804" />
                    <el-option label="Ubuntu 20.04" value="ubuntu2004" />
                    <el-option label="Windows Server 2019" value="windows2019" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="配置信息" name="specs">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="CPU(核)" prop="specs.cpu">
                  <el-input-number v-model="form.specs.cpu" :min="1" :max="128" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="内存(GB)" prop="specs.memory">
                  <el-input-number v-model="form.specs.memory" :min="1" :max="1024" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="磁盘(GB)" prop="specs.disk">
                  <el-input-number v-model="form.specs.disk" :min="10" :max="10240" style="width: 100%" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-tab-pane>
          
          <el-tab-pane label="连接信息" name="connection">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="SSH端口" prop="connection.sshPort">
                  <el-input-number v-model="form.connection.sshPort" :min="1" :max="65535" style="width: 100%" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="用户名" prop="connection.username">
                  <el-input v-model="form.connection.username" placeholder="请输入用户名" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="认证方式" prop="connection.authType">
              <el-radio-group v-model="form.connection.authType">
                <el-radio value="password">密码认证</el-radio>
                <el-radio value="key">密钥认证</el-radio>
              </el-radio-group>
            </el-form-item>
            <el-form-item 
              v-if="form.connection.authType === 'password'" 
              label="密码" 
              prop="connection.password"
            >
              <el-input 
                v-model="form.connection.password" 
                type="password" 
                placeholder="请输入密码" 
                show-password 
              />
            </el-form-item>
            <el-form-item 
              v-if="form.connection.authType === 'key'" 
              label="私钥" 
              prop="connection.privateKey"
            >
              <el-input 
                v-model="form.connection.privateKey" 
                type="textarea" 
                :rows="4" 
                placeholder="请输入私钥内容" 
              />
            </el-form-item>
          </el-tab-pane>
        </el-tabs>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio value="online">在线</el-radio>
            <el-radio value="offline">离线</el-radio>
            <el-radio value="maintenance">维护中</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="form.description"
            type="textarea"
            :rows="3"
            placeholder="请输入主机描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Search,
  Upload
} from '@element-plus/icons-vue'

// 注册图标组件
const iconComponents = {
  Plus,
  Search,
  Upload
}

// 接口定义
interface Host {
  id: string
  hostname: string
  ip: string
  hostType: string
  environment: string
  status: string
  specs: {
    cpu: number
    memory: number
    disk: number
  }
  os: string
  hostGroup: string
  connection: {
    sshPort: number
    username: string
    authType: string
    password?: string
    privateKey?: string
  }
  lastHeartbeat: string
  description: string
  createTime: string
}

interface SearchForm {
  name: string
  hostType: string
  environment: string
  status: string
}

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加主机')
const isEdit = ref(false)
const activeTab = ref('basic')
const selectedHosts = ref<Host[]>([])

// 搜索表单
const searchForm = reactive<SearchForm>({
  name: '',
  hostType: '',
  environment: '',
  status: ''
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 主机列表
const hostList = ref<Host[]>([])

// 表单数据
const form = reactive<Host>({
  id: '',
  hostname: '',
  ip: '',
  hostType: '',
  environment: '',
  status: 'online',
  specs: {
    cpu: 2,
    memory: 4,
    disk: 100
  },
  os: '',
  hostGroup: '',
  connection: {
    sshPort: 22,
    username: 'root',
    authType: 'password',
    password: '',
    privateKey: ''
  },
  lastHeartbeat: '',
  description: '',
  createTime: ''
})

// 表单引用
const formRef = ref()

// 选项数据
const hostTypeOptions = ref([
  { code: 'cloud_server', name: '云服务器' },
  { code: 'physical_server', name: '物理服务器' },
  { code: 'container_host', name: '容器主机' }
])

const environmentOptions = ref([
  { code: 'prod', name: '生产环境' },
  { code: 'test', name: '测试环境' },
  { code: 'dev', name: '开发环境' }
])

const hostGroupOptions = ref([
  { code: 'web', name: 'Web服务器组' },
  { code: 'db', name: '数据库服务器组' },
  { code: 'cache', name: '缓存服务器组' }
])

// 表单验证规则
const rules = {
  hostname: [
    { required: true, message: '请输入主机名', trigger: 'blur' }
  ],
  ip: [
    { required: true, message: '请输入IP地址', trigger: 'blur' },
    {
      pattern: /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
      message: '请输入正确的IP地址格式',
      trigger: 'blur'
    }
  ],
  hostType: [
    { required: true, message: '请选择主机类型', trigger: 'change' }
  ],
  environment: [
    { required: true, message: '请选择环境', trigger: 'change' }
  ],
  os: [
    { required: true, message: '请选择操作系统', trigger: 'change' }
  ]
}

// 模拟数据
const mockData: Host[] = [
  {
    id: 'HOST001',
    hostname: 'web-server-01',
    ip: '192.168.1.10',
    hostType: 'cloud_server',
    environment: 'prod',
    status: 'online',
    specs: { cpu: 4, memory: 8, disk: 200 },
    os: 'centos7',
    hostGroup: 'web',
    connection: {
      sshPort: 22,
      username: 'root',
      authType: 'password',
      password: '******'
    },
    lastHeartbeat: '2024-01-20 15:30:00',
    description: 'Web服务器节点1',
    createTime: '2024-01-15 10:00:00'
  },
  {
    id: 'HOST002',
    hostname: 'db-server-01',
    ip: '192.168.1.20',
    hostType: 'physical_server',
    environment: 'prod',
    status: 'online',
    specs: { cpu: 16, memory: 64, disk: 1000 },
    os: 'centos8',
    hostGroup: 'db',
    connection: {
      sshPort: 22,
      username: 'root',
      authType: 'key'
    },
    lastHeartbeat: '2024-01-20 15:29:45',
    description: '主数据库服务器',
    createTime: '2024-01-10 14:30:00'
  },
  {
    id: 'HOST003',
    hostname: 'cache-server-01',
    ip: '192.168.1.30',
    hostType: 'container_host',
    environment: 'test',
    status: 'maintenance',
    specs: { cpu: 2, memory: 4, disk: 50 },
    os: 'ubuntu2004',
    hostGroup: 'cache',
    connection: {
      sshPort: 22,
      username: 'ubuntu',
      authType: 'password',
      password: '******'
    },
    lastHeartbeat: '2024-01-20 14:15:20',
    description: 'Redis缓存服务器',
    createTime: '2024-01-08 09:15:00'
  }
]

// 获取主机类型颜色
const getHostTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    cloud_server: '#409eff',
    physical_server: '#67c23a',
    container_host: '#e6a23c'
  }
  return colorMap[type] || '#909399'
}

// 获取主机类型名称
const getHostTypeName = (type: string) => {
  const option = hostTypeOptions.value.find(item => item.code === type)
  return option?.name || type
}

// 获取环境标签类型
const getEnvironmentTagType = (env: string) => {
  const typeMap: Record<string, string> = {
    dev: 'info',
    test: 'warning',
    prod: 'danger'
  }
  return typeMap[env] || 'info'
}

// 获取环境名称
const getEnvironmentName = (env: string) => {
  const option = environmentOptions.value.find(item => item.code === env)
  return option?.name || env
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const statusMap: Record<string, string> = {
    online: 'success',
    offline: 'danger',
    maintenance: 'warning',
    error: 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态标签文本
const getStatusLabel = (status: string) => {
  const statusMap: Record<string, string> = {
    online: '在线',
    offline: '离线',
    maintenance: '维护中',
    error: '故障'
  }
  return statusMap[status] || status
}

// 获取主机列表
const fetchHostList = async () => {
  loading.value = true
  try {
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    // 应用搜索过滤
    let filteredData = [...mockData]
    if (searchForm.name) {
      filteredData = filteredData.filter(item =>
        item.hostname.includes(searchForm.name) || item.ip.includes(searchForm.name)
      )
    }
    if (searchForm.hostType) {
      filteredData = filteredData.filter(item => item.hostType === searchForm.hostType)
    }
    if (searchForm.environment) {
      filteredData = filteredData.filter(item => item.environment === searchForm.environment)
    }
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }

    pagination.total = filteredData.length
    const start = (pagination.currentPage - 1) * pagination.pageSize
    const end = start + pagination.pageSize
    hostList.value = filteredData.slice(start, end)
  } catch (error) {
    ElMessage.error('获取主机列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.currentPage = 1
  fetchHostList()
}

// 重置搜索
const handleReset = () => {
  Object.assign(searchForm, {
    name: '',
    hostType: '',
    environment: '',
    status: ''
  })
  pagination.currentPage = 1
  fetchHostList()
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.pageSize = size
  fetchHostList()
}

const handleCurrentChange = (page: number) => {
  pagination.currentPage = page
  fetchHostList()
}

// 选择变化处理
const handleSelectionChange = (selection: Host[]) => {
  selectedHosts.value = selection
}

// 显示添加对话框
const showAddDialog = () => {
  dialogTitle.value = '添加主机'
  isEdit.value = false
  activeTab.value = 'basic'
  resetForm()
  dialogVisible.value = true
}

// 显示编辑对话框
const showEditDialog = (row: Host) => {
  dialogTitle.value = '编辑主机'
  isEdit.value = true
  activeTab.value = 'basic'
  Object.assign(form, { ...row })
  dialogVisible.value = true
}

// 显示详情对话框
const showDetailDialog = (row: Host) => {
  // 这里可以实现详情对话框
  ElMessage.info('详情功能开发中...')
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: '',
    hostname: '',
    ip: '',
    hostType: '',
    environment: '',
    status: 'online',
    specs: {
      cpu: 2,
      memory: 4,
      disk: 100
    },
    os: '',
    hostGroup: '',
    connection: {
      sshPort: 22,
      username: 'root',
      authType: 'password',
      password: '',
      privateKey: ''
    },
    lastHeartbeat: '',
    description: '',
    createTime: ''
  })
  formRef.value?.resetFields()
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        // 模拟API调用
        await new Promise(resolve => setTimeout(resolve, 1000))

        ElMessage.success(`${isEdit.value ? '更新' : '创建'}成功`)
        dialogVisible.value = false
        fetchHostList()
      } catch (error) {
        ElMessage.error(`${isEdit.value ? '更新' : '创建'}失败`)
      }
    }
  })
}

// 连接主机
const handleConnect = (row: Host) => {
  ElMessage.info(`正在连接主机 ${row.hostname}...`)
  // 这里可以实现SSH连接功能
}

// 删除主机
const handleDelete = async (row: Host) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除主机 "${row.hostname}" 吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))

    ElMessage.success('删除成功')
    fetchHostList()
  } catch (error) {
    // 用户取消操作
  }
}

// 批量导入
const handleBatchImport = () => {
  ElMessage.info('批量导入功能开发中...')
}

// 批量编辑
const handleBatchEdit = () => {
  ElMessage.info(`批量编辑 ${selectedHosts.value.length} 台主机`)
}

// 批量连接
const handleBatchConnect = () => {
  ElMessage.info(`批量连接 ${selectedHosts.value.length} 台主机`)
}

// 批量删除
const handleBatchDelete = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedHosts.value.length} 台主机吗？此操作不可恢复！`,
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))

    ElMessage.success('批量删除成功')
    selectedHosts.value = []
    fetchHostList()
  } catch (error) {
    // 用户取消操作
  }
}

// 组件挂载时获取数据
onMounted(() => {
  fetchHostList()
})
</script>

<style scoped>
.host-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-bar {
  margin-bottom: 20px;
  padding: 20px;
  background: rgba(255, 255, 255, 0.02);
  border-radius: 8px;
  border: 1px solid rgba(120, 220, 255, 0.1);
}

.specs-info {
  font-size: 12px;
  color: var(--tech-text-secondary);
}

.specs-info div {
  margin-bottom: 2px;
}

.batch-actions {
  margin-top: 15px;
  padding: 10px 15px;
  background: rgba(64, 158, 255, 0.1);
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 15px;
}

.batch-actions span {
  color: var(--tech-accent-color);
  font-weight: 500;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>
